<?php
namespace app\common\model\food;

use app\common\model\BaseModel;
use app\common\model\User;
use app\common\model\Record;
use app\common\model\Applet;
use app\common\model\Setting as SettingModel;
use addons\food\library\Order as Ev;
use think\facade\Db;
use hema\wechat\Pay as WxPay;
use hema\delivery\Driver as Delivery;

/**
 * 公众号模型
 */
class Order extends BaseModel
{
    // 定义表名
    protected $name = 'food_order';

    // 定义主键
    protected $pk = 'order_id';

    // 追加字段
    protected $append = [
        'user'    
    ];

    /**
     * 模型基类初始化
     */
    public static function init()
    {
        parent::init();
        (new Ev((int)self::$applet_id))->listen();
    }

    /**
     * 订单商品列表
     */
    public function goods()
    {
        return $this->hasMany('app\\common\\model\\food\\OrderGoods','order_id');
    }

    /**
     * 关联订单收货地址表
     */
    public function address()
    {
        return $this->hasOne('app\\common\\model\\food\\OrderAddress','order_id','order_id');
    }

    /**
     * 关联订单配送表
     */
    public function delivery()
    {
        return $this->hasOne('app\\common\\model\\food\\OrderDelivery','order_id','order_id');
    }

    /**
     * 关联评论表
     */
    public function comment()
    {
        return $this->hasOne('app\\common\\model\\food\\Comment','order_id','order_id');
    }
    
    /**
     * 关联餐桌/包间表
     */
    public function table()
    {
        return $this->belongsTo('app\\common\\model\\food\\Table','table_id');
    }
    
    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }

    /**
     * 格式化到店时间
     */
    public function getArriveTimeAttr($value)
    {
        return ['text' => date("Y-m-d H:i:s",$value), 'value' => $value];
    }
    
    /**
     * 用户表
     */
    public function getUserAttr($value,$data)
    {
        return User::withoutGlobalScope()->find($data['user_id']);
    }

    /**
     * 订单来源
     */
    public function getSourceAttr($value)
    {
        $status = [10 => '自助点单', 20 => '代客点单', 30 => '平台点单'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 订单类型
     */
    public function getOrderModeAttr($value)
    {
        $status = [10 => '堂食', 20 => '外卖', 30 => '自取'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 付款状态
     */
    public function getPayStatusAttr($value)
    {
        $status = [10 => '待付款', 20 => '已付款', 30 => '后付款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 商家状态
     */
    public function getShopStatusAttr($value)
    {
        $status = [10 => '待接单', 20 => '已接单', 30 => '已接单'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 配送状态
     */
    public function getDeliveryStatusAttr($value,$data)
    {
        if($data['order_mode'] == 10){
            $status = [10 => '备餐中', 20 => '启菜中', 30 => '上餐完毕'];
        }
        if($data['order_mode'] == 20){
            $status = [10 => '备餐中', 20 => '配送中', 30 => '已配送'];
        }
        if($data['order_mode'] == 30){
            $status = [10 => '备餐中', 20 => '待取餐', 30 => '已取餐'];
        }
        return ['text' => $status[$value], 'value' => $value];
    }
    

    /**
     * 收货状态
     */ 
    public function getReceiptStatusAttr($value,$data)
    {
        if($data['order_mode'] == 20){
            $status = [10 => '待收货', 20 => '已收货'];
        }else{
            $status = [10 => '待完成', 20 => '已完成'];
        }
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 退款状态
     */ 
    public function getRefundStatusAttr($value)
    {
        $status = [10 => '待退款', 20 => '已退款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 订单状态
     */
    public function getOrderStatusAttr($value)
    {
        $status = [10 => '进行中', 20 => '被取消', 30 => '已完成', 40 => '退款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否评价
     */
    public function getIsCmtAttr($value)
    {
        $status = ['待评价', '已评价'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 按照分类获取单列表
     * $type 类别 all=所有 payment=待付款 comment=待评价 refund=退款/售后
     */
    public function getList(string $dataType='all', $shop_id = 0, $user_id = 0, string $search = '')
    {
        // 筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id; 
        $user_id > 0 && $filter['user_id'] = $user_id; 
        $model = $this->with(['goods.image','shop','table','comment','delivery'])->order(['order_id' => 'desc']);
        switch ((string)$dataType) {
            case 'all'; //全部
                break;
            case 'payment'; //待付款
                $filter['pay_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'collection'; //待收款
                $filter['pay_status'] = 30;
                $filter['order_status'] = 10;
                break;
            case 'shop';//待接单
                $model->where('pay_status','>',10);
                $filter['shop_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'delivery';//待配送
                $model->where('shop_status','>',10);
                $filter['delivery_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'receipt';//待收货
                $filter['pay_status'] = 20;
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 30;
                $filter['receipt_status'] = 10;
                break;
            case 'cancel';//被取消
                $filter['order_status'] = 20;
                break;
            case 'complete';//已完成
                $filter['order_status'] = 30;
                break;
            case 'comment';//待评价
                $filter['is_cmt'] = 0;
                $filter['order_status'] = 30;
                break;
            case 'refund';//全部退款
                $filter['order_status'] = 40;
                break;
            case 'refund10';//待退款
                $filter['refund_status'] = 10;
                $filter['order_status'] = 40;
                break;
            case 'refund20';//已退款
                $filter['refund_status'] = 20;
                $filter['order_status'] = 40;
                break;
        }
        return $model->where($filter)->paginate(['list_rows'=>15,'query' => request()->param()]); 
    }

    /**
     * 订单详情
     */
    public static function detail($id)
    {
        return self::with(['goods' => ['image', 'spec', 'goods'], 'address', 'shop', 'table','delivery'])
            ->where(['order_id' => $id])
            ->find();
    }

    /**
     * 商家接单
     */
    public function setShopStatus()
    {
        //发送商家接单订阅消息
        food_post_tpl('receive',$this->order_id);
        return $this->save([
            'shop_status' => 20,
            'shop_time' => time()
        ]);
    }

    /**
     * 确认收到用户付款（后付费用户）
     */
    public function collection()
    {
        // 开启事务
        Db::startTrans();
        try {
            //如果该用户存在则执行下列操作，代客非会员下单不会执行
            if($user = User::withoutGlobalScope()->where('user_id',$this->user_id)->find()){
                $user->pay = ['inc', $this->pay_price];//增加消费金额
                $user->score = ['inc', $this->pay_price];//增加消费积分
                $user->save();
                //添加交易记录
                $record = new Record;
                $record->save([
                    'order_no' => $this->order_no,
                    'money' => $this->pay_price,
                    'user_id' => $this->user_id,
                    'shop_id' => $this->shop_id,
                    'applet_id' => $this->applet_id,
                    'type' => 20,//现金（默认）
                    'mode' => 20,//后台操作
                    'action' => 40,//消费
                    'remark' => '当面付款'
                ]);
            }
            $this->save(['pay_status' => 20,'pay_time' => time()]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    
     /**
     * 设置配送状态
     */
    public function setDeliveryStatus(array $data = [])
    {
        $delivery = [
            'delivery_status' => $data['delivery_status'],
            'delivery_time' => time()
        ];
        if($data['delivery_status'] == 40){
            food_post_tpl('delivery',$this->order_id);//骑手配送订阅消息
        }
        if($data['delivery_status'] == 50){
            $delivery['status'] = 30;
            $this->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ]);
        }
        return $this->delivery->save($delivery);
    }

    /**
     * 确认发货
     */
    public function setDelivery($company='', $shop_clerk_id='')
    {
        // 开启事务
        Db::startTrans();
        try {
            //外卖配送
            if($this->order_mode['value'] == 20){
                if($this->delivery_status['value']==10){
                    $data = [
                        'shop_status' => 30,//已推送外卖订单
                        'shop_time' => time(),
                        'delivery_status' => 20
                    ];
                    if($company == 'self'){
                        //是否开启骑手抢单
                        //if($this->shop['is_grab']['value'] == 0){
                            if(empty($shop_clerk_id)){
                                $clerk = ShopClerk::where(['shop_id' => $this->shop_id,'status' => 20])->find(); //获取店员信息
                            }else{
                                $clerk = ShopClerk::get($shop_clerk_id); //获取店员信息
                            }
                            $dev = [
                                'linkman' => $clerk['real_name'],
                                'phone' => $clerk['mobile'],
                                'delivery_status' => 30,  //已到店
                                'order_no' => $this->order_no,
                            ];
                            //骑手接单提醒
                            food_post_tpl('horseman',$this->order_id);
                        //}else{
                            //抢单通知
                            //sand_grab_msg($this);
                        //}
                    }
                    if($company == 'sf'){
                        $sf = new Delivery('sf');
                        $user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度
		                $shop_location = explode(',',$this['shop']['coordinate']);//拆分门店定位经纬度
		                $time = time();
                		$post_data = [
                			'shop_id' => $this['shop']['sf_shop_id'],//$this->shop_id,//店铺ID
                			'shop_type' => 1,//店铺ID类型 1：顺丰店铺ID ；2：接入方店铺ID
                			'shop_order_id' => $this['order_no'],//商家订单号	不允许重复
                			'order_source' => $this['shop']['shop_name'],//订单接入来源
                			'order_sequence' => '外卖'.$this['row_no'].'号',//取货序号
                			'lbs_type' => 2,//坐标类型	1：百度坐标，2：高德坐标
                			'pay_type' => 1,//用户支付方式	1：已付款 0：货到付款
                			'receive_user_money' => 0,//代收金额,单位：分
                			'order_time' => $this['pay_time'],//用户下单时间	秒级时间戳
                			'is_appoint' => 0,//是否是预约单,0：非预约单；1：预约单
                			'expect_time' => $time + 1800,//用户期望送达时间	预约单需必传,秒级时间戳
                			'is_insured' => 0,//是否保价，0：非保价；1：保价
                			'declared_value' => 0,//保价金额,单位：分
                			'is_person_direct' => 0,//是否是专人直送订单，0：否；1：是
                			'declared_value' => 0,//保价金额	单位：分
                			'gratuity_fee' => 0,//订单小费，不传或者传0为不加小费	单位分，加小费最低不能少于100分
                			'remark' => $this['message'],//订单备注
                			'rider_pick_method' => 1,//物流流向	1：从门店取件送至用户,2：从用户取件送至门店
                			'return_flag' => 511,	//返回字段控制标志位（二进制）	1:商品总价格，2:配送距离，4:物品重量，8:起送时间，16:期望送达时间，32:支付费用，64:实际支持金额，128:优惠卷总金额，256:结算方式,例如全部返回为填入511
                			'push_time' => $time,
                			'version' => 17,
                			//发货店铺信息；Obj,平台级开发者需要传入
                			'shop' => [
                				'shop_name' => $this['shop']['shop_name'],//店铺名称
                				'shop_phone' => $this['shop']['phone'],//店铺电话
                				'shop_address' => $this['shop']['address'],//店铺地址
                				'shop_lng' => $shop_location[1],//店铺经度
                				'shop_lat' => $shop_location[0]//店铺纬度		
                			],
                			'receive' => [
                				'user_name' => $this['address']['name'],//用户姓名
                				'user_phone' => $this['address']['phone'],//用户电话
                				'user_lng' => $user_location[1],//用户地址经度
                				'user_lat' => $user_location[0],//用户地址纬度
                				'user_address' => $this['address']['detail'], //用户地址
                				'city_name' => $this['address']['city'] //发单城市,用来校验是否跨城；请填写城市的中文名称，如北京市
                			],
                			'order_detail' => [
                				'total_price' => $this['pay_price']*100,//用户订单总金额（单位：分）
                				'product_type' => 1, //物品类型,测试店铺请填写1，否则会造成【没有匹配的计价规则或计价规则已失效】
                				'user_money' => $this['pay_price']*100, //实收用户金额（单位：分）
                				'shop_money' => $this['pay_price']*100,//实付商户金额（单位：分）
                				'weight_gram' => 1,//物品重量（单位：克）
                				'volume_litre' => 5,//物品体积（单位：升）
                				'delivery_money' => 1,//商户收取的配送费（单位：分）
                				'product_num' => sizeof($this['goods']),//物品个数
                				'product_type_num' => sizeof($this['goods'])//物品种类个数
                			]
                		];
                		$product_detail = [];//商品列表详情
                		foreach ($this['goods'] as $item){
                			$product_detail[] = [
                				'product_name' => $item['goods_name'],//物品名称
                				'product_id' => $item['goods_id'],//物品ID
                				'product_num' => $item['total_num'],//物品数量
                				'product_price' => $item['goods_price'],//物品价格
                				'product_unit' => '个',//物品单位
                				'product_remark' => '',//备注
                				'item_detail'=> ''//详情
                			];
                		}
                		$post_data['order_detail']['post_data'] = $product_detail;//商品详情
                        if($result = $sf->addOrder($post_data)){
                            $real_pay_money = (int)$result['result']['real_pay_money'];//配送费
                            $real_pay_money = round($real_pay_money / 100,2); //四舍五入保留两位小数
                            $dev = [
                                'price' => $real_pay_money, //配送费
                                'distance' => $result['result']['delivery_distance_meter'] * 100,//配送距离
                                'order_no' => $result['result']['sf_order_id'] //顺丰订单号（标准默认为int，可以设置为string）
                            ];
                        }else{
                            $this->error = $sf->getError();
                            return false; 
                        }
                    }
                    if($company == 'dada'){
                        $dada = new Delivery('dada');
                        $user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度
		                $shop_location = explode(',',$this['shop']['coordinate']);//拆分门店定位经纬度
		                $city_code = $dada->getCiytCode($this['shop']['city']);
		                $post_data = [
                			'shop_no' => $this['shop']['dada_shop_id'],//是 门店编号
                			'origin_id' => $this['order_no'],//是 第三方订单ID
                			'city_code' => $city_code,//是 订单所在城市的code
                			'cargo_price' => $this['pay_price'],//是 订单金额
                			'is_prepay' => 0,//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
                			'receiver_name' => $this['address']['name'],//是 收货人姓名
                			'receiver_address' => $this['address']['detail'],//是 收货人地址
                			'callback' => base_url() . 'api/food.delivery/dada',//是 回调URL
                			'receiver_lat' => $user_location[0], //否 收货人地址纬度
                			'receiver_lng' => $user_location[1],//否 收货人地址经度
                			'receiver_phone' => $this['address']['phone'],//否 收货人手机号
                			//'tips' => 0,//否 小费（单位：元，精确小数点后一位）
                			'info' => $this['message'],//否 订单备注
                			//'cargo_type' => 1,//否 订单商品类型：食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5
                			'cargo_weight' => 0.1,//是	订单重量（单位：Kg）
                			//'origin_mark_no' => '河马云店',//否	订单来源编号
                			//'is_use_insurance' => 0,//是否使用保价费（0：不使用保价，1：使用保价； 同时，请确保填写了订单金额（cargo_price））	
                		];
                        if($pre = $dada->preOrder($post_data)){
                            $dada_config = get_addons_config('dada');//获取配送设置
                            //如果是余额支付配送费
                            if($dada_config['pay_mode'] == 0){
                                $applet = Applet::detail();
                                if($user = User::withoutGlobalScope()->where('user_id',$applet['user_id'])->find()){
                                    //判断商家余额
                                    if($user['money'] < $pre['dada']['result']['fee']){
                                        //发送余额不足模板消息************************
                                        $this->error = '账户余额不足';
                                        return false; 
                                    }
                                    //扣取配送费
                                    $user->money = ['dec',$pre['dada']['result']['fee']];
                                    $user->pay = ['inc', $pre['dada']['result']['fee']];//增加消费金额
		                            $user->score = ['inc', $pre['dada']['result']['fee']];//增加积分
                                    $user->save();
                                    $record = new Record;
                                    $record->save([
                                        'user_type' => 20,//商家
                                        'action' => 20,//扣减
                                        'order_no' => $this->order_no,
                                        'money' => $pre['dada']['result']['fee'],
                                        'remark' => '第三方配送费',
                                        'user_id' => $applet['user_id'] 
                                    ]);
                                }
                            }
                            if($result = $dada->addOrder(['delivery_no' => $pre['dada']['result']['deliveryNo']])){
                                $dev = [
                                    'price' => $pre['dada']['result']['fee'], //配送费
                                    'distance' => (int)$pre['dada']['result']['distance'],//配送距离
                                    'order_no' => $this->order_no //商家单号
                                    //'order_no' => $pre['dada']['result']['deliveryNo'] //达达单号
                                ];
                            }else{
                                $this->error = $dada->getError();
                                return false;
                            }
                        }else{
                            $this->error = $dada->getError();
                            return false; 
                        } 
                    }
                    if($company == 'uu'){
                        $uu = new Delivery('uu');
                        $user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度
		                $shop_location = explode(',',$this['shop']['coordinate']);//拆分门店定位经纬度
		                $post_data = [
                			'origin_id' => $this['order_id'],//第三方对接平台订单id
                			'from_address' => $this['shop']['address'],//起始地址
                			//'from_usernote' => '',//起始地址具体门牌号(可为空)
                			'to_address' => $this['address']['detail'],//目的地址
                			//'to_usernote' => '',//目的地址具体门牌号(可为空)
                			'city_name' => $this['shop']['city'],//订单所在城市名 称(如郑州市就填”郑州市“，必须带上“市”)
                			'county_name' => $this['shop']['district'],//订单所在县级地名称(如金水区就填“金水区”)(可为空)
                			'subscribe_type' => '0',//预约类型 0实时订单 1预约取件时间(可为空)
                			//'subscribe_time' => '',//预约时间（如：2015-06-18 12:00:00）没有可以传空字符串(可为空)
                			'send_type' => '0',//订单小类 0帮我送(默认) 1帮我买
                			'to_lat' => $user_location[0],//目的地坐标纬度，如果无，传0(坐标系为百度地图坐标系)
                			'to_lng' => $user_location[1],//目的地坐标经度，如果无，传0(坐标系为百度地图坐标系)
                			'from_lat' => $shop_location[0],//起始地坐标纬度，如果无，传0(坐标系为百度地图坐标系)
                			'from_lng' => $shop_location[1] //起始地坐标经度，如果无，传0(坐标系为百度地图坐标系)	
                		];
                        if($pre = $uu->preOrder($post_data)){
                            $uu_config = get_addons_config('uu');//获取配送设置
                            //如果是余额支付配送费
                            if($uu_config['pay_mode'] == 0){
                                $applet = Applet::detail();
                                if($user = User::withoutGlobalScope()->where('user_id',$applet['user_id'])->find()){
                                    //判断商家余额
                                    if($user['money'] < $pre['uu']['need_paymoney']){
                                        //发送余额不足模板消息************************
                                        $this->error = '账户余额不足';
                                        return false; 
                                    }
                                    //扣取配送费
                                    $user->money = ['dec',$pre['uu']['need_paymoney']];
                                    $user->pay = ['inc', $pre['uu']['need_paymoney']];//增加消费金额
		                            $user->score = ['inc', $pre['uu']['need_paymoney']];//增加积分
                                    $user->save();
                                    $record = new Record;
                                    $record->save([
                                        'user_type' => 20,//商家
                                        'action' => 20,//扣减
                                        'order_no' => $this->order_no,
                                        'money' => $pre['uu']['need_paymoney'],
                                        'remark' => '第三方配送费',
                                        'user_id' => $applet['user_id'] 
                                    ]);
                                }
                            }
                            $post_data = [
                    			'price_token' => $pre['uu']['price_token'],//金额令牌，计算订单价格接口返回的price_token
                    			'order_price' => $pre['uu']['total_money'],//订单金额，计算订单价格接口返回的total_money
                    			'balance_paymoney' => $pre['uu']['need_paymoney'],//实际余额支付金额计算订单价格接口返回的need_paymoney
                    			'receiver' => $this['address']['name'],//收件人
                    			'receiver_phone' => $this['address']['phone'],//收件人电话 手机号码；虚拟号码格式（手机号_分机号码）例如：13700000000_1111
                    			'callback_url' => base_url() . 'api/food.delivery/uu',//订单提交成功后及状态变化的回调地址
                    			'push_type' => '0',//推送方式（0 开放订单，2测试订单）默认传0即可
                    			'special_type' => '0',//是否需要保温箱 1需要 0不需要
                    			'callme_withtake' => '0',//取件是否给我打电话 1需要 0不需要
                    			'pubusermobile' => $this['shop']['phone'],//发件人电话，（如果为空则是用户注册的手机号）
                    			'pay_type' => '1' //支付方式：1=企业支付 0账户余额支付（企业余额不足自动转账户余额支付）	
                    		];
                    		!empty($this['message']) && $post_data['note'] = $this['message'];//订单备注 最长140个汉字
                            if($result = $uu->addOrder($post_data)){
                                $dev = [
                                    'price' => $pre['uu']['need_paymoney'], //配送费
                                    'distance' => $pre['uu']['distance'],  //配送距离
                                    'order_no' => $result['ordercode']
                                ];
                            }else{
                                $this->error = $uu->getError();
                                return false;
                            }
                        }else{
                            $this->error = $uu->getError();
                            return false;
                        } 
                    }
                    if($company == 'make'){
                        $make = new Delivery('make');
                        $post_data = [
                			'fromcoord' => $this['shop']['coordinate'],//起点地址坐标
                            'tocoord' => $this['address']['location'],//终点地址坐标
                            'shop_id' => $this['shop']['make_shop_id'] //店铺ID	
                		];
                        if($pre = $make->preOrder($post_data)){
                            $make_config = get_addons_config('make');//获取配送设置
                            //如果是余额支付配送费
                            if($make_config['pay_mode'] == 0){
                                $applet = Applet::detail();
                                if($user = User::withoutGlobalScope()->where('user_id',$applet['user_id'])->find()){
                                    //判断商家余额
                                    if($user['money'] < $pre['make']['data']['total_price']){
                                        //发送余额不足模板消息************************
                                        $this->error = '账户余额不足';
                                        return false; 
                                    }
                                    //扣取配送费
                                    $user->money = ['dec',$pre['make']['data']['total_price']];
                                    $user->pay = ['inc', $pre['make']['data']['total_price']];//增加消费金额
    		                        $user->score = ['inc', $pre['make']['data']['total_price']];//增加积分
                                    $user->save();
                                    $record = new Record;
                                    $record->save([
                                        'user_type' => 20,//商家
                                        'action' => 20,//扣减
                                        'order_no' => $this->order_no,
                                        'money' => $pre['make']['data']['total_price'],
                                        'remark' => '第三方配送费',
                                        'user_id' => $applet['user_id'] 
                                    ]);
                                }
                            }
                            
		                    //附加数据json格式，回调返回该参数
                    		$attach = [
                    			'name' => $this['shop']['shop_name']
                    		];
                    		$post_data = [
                    			'shop_id' => $this['shop']['make_shop_id'],//$this->shop_id,//店铺ID
                    			'goods_name' => $this['shop']['shop_name'],//商品名称
                    			'order_no' => $this['order_no'],//商家订单号	不允许重复
                    			'notify_url' => base_url() . 'api/food.delivery/make',//回调地址
                    			'pay_price' => $pre['make']['data']['total_price'],//跑腿支付金额
                    			'total_price' => $pre['make']['data']['total_price'],//跑腿总金额
                    			'pick_time' => date("Y-m-d H:i",time()),//取件时间 格式2020-09-30 00:00
                    			'remark' => $this['message'],//订单备注
                    			'attach' => json_encode($attach,JSON_UNESCAPED_UNICODE),
                    		];
                    		$user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度
		                    $shop_location = explode(',',$this['shop']['coordinate']);//拆分门店定位经纬度
                    		//地址信息
                    		$address = [
                    			'begin_detail' => $this['shop']['address'],
                    			'begin_address' => $this['shop']['province'] . $this['shop']['city'] . $this['shop']['district'] . $this['shop']['address'],
                    			'begin_lat' => $shop_location[0],
                    			'begin_lng' => $shop_location[1],
                    			'begin_username' => $this['shop']['linkman'],
                    			'begin_phone' => $this['shop']['phone'],
                    			'end_detail' => $this['address']['detail'],
                    			'end_address' => $this['address']['province'] . $this['address']['city'] . $this['address']['district'] . $this['address']['detail'],
                    			'end_lat' => $user_location[0],
                    			'end_lng' => $user_location[1],
                    			'end_username' => $this['address']['name'],
                    			'end_phone' => $this['address']['phone']
                    		];
                    		$post_data['address'] = json_encode($address,JSON_UNESCAPED_UNICODE);
                    		//商品详情
                    		$goods = [];
                    		foreach ($this['goods'] as $vo) {
                    			$goods[] = [
                    				'name' => $vo['goods_name'],//物品名称
                    				'price' => $vo['goods_price'],//物品价格
                    				'num' => $vo['total_num'],//物品数量
                    			];
                    		}
                    		$post_data['goods'] = json_encode($goods,JSON_UNESCAPED_UNICODE);
                            if($result = $make->addOrder($post_data)){
                                $dev = [
                                    'price' => $pre['make']['data']['total_price'], //配送费
                                    'distance' => $pre['make']['data']['distance'] * 1000,//配送距离
                                    'order_no' => $result['data']['order_number']
                                ];
                            }else{
                                $this->error = $make->getError();
                                return false;
                            }
                        }else{
                            $this->error = $make->getError();
                            return false; 
                        } 
                    }
                    $dev['company'] = $company;
                    $dev['delivery_time'] = time();
                    $dev['shop_id'] = $this->shop_id;
                    $dev['applet_id'] = $this->applet_id;
                    $this->delivery()->save($dev);
                }else{
                    //外卖配送完毕
                    $this->delivery->save([
                        'delivery_status' => 50,
                        'delivery_time' => time(),
                        'status' => 30
                    ]);
                    $data = [
                        'delivery_status' => 30
                    ];
                }
            }else{
                //判断堂食排号点餐
                if($this->order_mode['value']==10 AND !empty($this->row_no)){
                    Device::push($this->shop_id,'rows',$this->row_no);//叫号
                }
                //非外卖配送
                $data = [
                    'delivery_status' => 30
                ];
                if($this->order_mode['value'] == 10 AND $this->row_no == ''){
                    //发送模板消息，订单完成通知
                    food_post_tpl('finish',$this->order_id);
                }else{
                    //发送模板消息，取餐提醒通知
                    food_post_tpl('take',$this->order_id);
                }   
            }
            $data['delivery_time'] = time();
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    
    /**
     * 确认收货 - 清台
     */
    public function receipt()
    {
        food_post_tpl('finish',$this->order_id);
        //堂食扫码释放餐桌
        if($this->table_id > 0){
            Table::where(['table_id' => $this->table_id])->update(['status' => 10]);
        }
        //账单分账
        $values = SettingModel::getItem('wxpay',$this->applet_id);
        $wxpay = new WxPay($values);
        $wxpay->divide($this);//进行分账
        return $this->save([
            'receipt_status' => 20,
            'receipt_time' => time(),
            'order_status' => 30
        ]);
    }
    
    /**
     * 取消已经推送的外卖订单
     */
    public function cancelDelivery()
    {
        $data = [
            'shop_status' => 20,
            'shop_time' => time(),
            'delivery_status' => 10,
            'delivery_time' => 10
        ];
        if($this->delivery['company']['value'] != 'self'){
            $dv = new Delivery($this->delivery['company']['value']);
            if(!$result = $dv->cancelOrder($this->delivery['order_no'])){
                $this->error = $dv->getError();
                return false;
            }
        }
         // 开启事务
        Db::startTrans();
        try {
            //退款 --- 待补充
            OrderDelivery::where('order_delivery_id',$this->delivery['order_delivery_id'])->delete();
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 退款处理
     */
    public function refund($is_refund = 0)
    {
        if($this->refund_price > $this->pay_price){
            $this->error = '退款金额不可大于实付金额';
            return false;
        }
        //同意退款
        if($is_refund==1){
            // 开启事务
            Db::startTrans();
            try {
                //判断支付方式
                if(empty($this->transaction_id)){
                    //余额变动
                    $user = User::getUser(['user_id' => $this->user_id]);
                    $user->money = ['inc',$this->refund_price];//返回余额
                    if($this->refund_price > $user->pay){
                        $pay = $user->pay;
                    }else{
                        $pay = $this->refund_price;
                    }
                    $user->pay = ['dec', $pay];//扣减消费金额
                    if($this->refund_price > $user->score){
                        $score = $user->score;
                    }else{
                        $score = $this->refund_price;
                    }
                    $user->score = ['dec', $score];//扣减积分
                    $user->save();
                    //添加交易记录
                    $record = new Record;
                    $record->save([
                        'order_no' => $this['order_no'],
                        'money' => $this['refund_price'],
                        'user_id' => $this['user_id'],
                        'shop_id' => $this['shop_id'],
                        'applet_id' => $this['applet_id'],
                        'action' => 60,//退款
                        'remark' => '订单退款'
                    ]);
                    //更新商品库存、销量
                    $this->save([
                        'refund_status' => 20,
                        'refund_time' => time()
                    ]);
                    //发送退款申请状态提醒订阅消息
                    food_post_tpl('refund',$this->order_id);
                }else{
                    //微信退款处理
                    $values = SettingModel::getItem('wxpay');
                    $WxPay = new WxPay($values);
                    $result = $WxPay->refund($this->order_no,$this->transaction_id,$this->pay_price,$this->refund_price,$this->refund_desc,'api/food.notify/orderRefund');
                    if($result){
                        $this->error = $result;
                        return false;
                    }
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
            }
            return false;
        }
        //拒绝退款
        // 开启事务
        Db::startTrans();
        try {
            OrderGoods::where('order_id',$this->order_id)->update([
                'refund_num' => 0,
                'refund_price' => 0
            ]);
            $this->save([
                'order_status' => 10,
                'refund_status' => 10,
                'refund_price' => 0
            ]);
            //发送退款申请状态提醒订阅消息
            food_post_tpl('refund',$this->order_id);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 清除订单记录
     */
    public function remove($order_id)
    {
        $filter['order_id'] = $order_id;
        // 开启事务
        Db::startTrans();
        try {
            $this->withoutGlobalScope()->where($filter)->delete();
            OrderAddress::withoutGlobalScope()->where($filter)->delete();
            OrderDelivery::withoutGlobalScope()->where($filter)->delete();
            OrderGoods::withoutGlobalScope()->where($filter)->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    /**
     * 获取订单分类统计
     */
    public function getOrderClassCount($dataType='all',$shop_id='',$user_id='')
    {
        // 筛选条件
        $filter = [];
        !empty($shop_id) && $filter['shop_id'] = $shop_id;
        !empty($user_id) && $filter['user_id'] = $user_id;
        !empty($user_id) && $filter['user_id'] = $user_id;
        $model = $this->order(['order_id' => 'desc']);
        // 订单数据类型
        switch ((string)$dataType) {
            case 'all'; //全部
                break;
            case 'payment'; //待付款
                $filter['pay_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'collection'; //待收款
                $filter['pay_status'] = 30;
                $filter['order_status'] = 10;
                break;
            case 'shop';//待接单
                $model->where('pay_status','>',10);
                $filter['order_status'] = 10;
                $filter['shop_status'] = 10;
                break;
            case 'delivery';//待配送
                $model->where('shop_status','>',10);
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 10;
                break;
            case 'receipt';//待收货
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 30;
                $filter['receipt_status'] = 10;
                break;
            case 'cancel';//被取消
                $filter['order_status'] = 20;
                break;
            case 'complete';//已完成
                $filter['order_status'] = 30;
                break;
            case 'comment';//待评价
                $filter['is_cmt'] = 0;
                $filter['order_status'] = 30;
                break;
            case 'refund';//全部退款
                $filter['order_status'] = 40;
                break;
            case 'refund10';//待退款
                $filter['refund_status'] = 10;
                $filter['order_status'] = 40;
                break;
            case 'refund20';//已退款
                $filter['refund_status'] = 20;
                $filter['order_status'] = 40;
                break;
        }
        return $model->where($filter)->count();
    }

    /**
     * 根据时间段统计数量
     */
    public static function getDateCount($shop)
    {
        $self = new static;
         // 筛选条件
        $filter = [];
        $shop['shop_id'] > 0 && $filter['shop_id'] = $shop['shop_id'];
        $applet_id = $self::$applet_id;
        $applet_id > 0 && $filter['applet_id'] = $applet_id;
        $count = array();
        $count['count'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->count();
        $count['tang'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_mode'=>10])->count();
        $count['qu'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_mode' =>30])->count();
        $count['wai'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_mode' =>20])->count();
        $count['refund'] = self::where('create_time','>',$shop['star'])->where('create_time','<',$shop['end'])->where($filter)->where(['order_status' => 40])->count();
        return $count;
    }

    /**
     * 根据条件统计数量
     */
    public static function getCount($shop_id = 0)
    {
        $self = new static;
        // 筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        $applet_id = $self::$applet_id;
        empty($applet_id) && $filter['applet_id'] = 0;
        $count = array();
        $count[0]['count'] = self::where($filter)->count();//全部
        $count[0]['refund'] = self::where($filter)->where(['order_status' => 40,'refund_status'=>10])->count();//待退款
        //今天
        $star = strtotime(date('Y-m-d 00:00:00',time()));
        $count[1]['count'] = self::where($filter)->where('create_time','>',$star)->count();
        $count[1]['tang'] = self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$star)->count();
        $count[1]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$star)->count();
        $count[1]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$star)->count();
        $count[1]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$star)->count();
        //昨天
        $star = strtotime("-1 day");
        $end = strtotime(date('Y-m-d 00:00:00',time()));
        $count[2]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['tang'] = self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[2]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //前天
        $star = strtotime("-2 day");
        $end = strtotime("-1 day");
        $count[3]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-4天
        $star = strtotime("-3 day");
        $end = strtotime("-2 day");
        $count[4]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-5天
        $star = strtotime("-4 day");
        $end = strtotime("-3 day");
        $count[5]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-6天
        $star = strtotime("-5 day");
        $end = strtotime("-4 day");
        $count[6]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //-7天
        $star = strtotime("-6 day");
        $end = strtotime("-5 day");
        $count[7]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        //本月起至时间 - 月度统计 
        $end = mktime(0,0,0,date('m'),1,date('y')); 
        $count[8]['count'] = self::where($filter)->where('create_time','>',$end)->count();
        $count[8]['tang'] =self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$end)->count();
        $count[8]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$end)->count();
        $count[8]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$end)->count();
        $count[8]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$end)->count();
        //上月开始  
        $star = mktime(0,0,0,date('m')-1,1,date('y')); 
        $count[9]['count'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['tang'] = self::where($filter)->where(['order_mode'=> 10])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['qu'] = self::where($filter)->where(['order_mode' => 30])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['wai'] = self::where($filter)->where(['order_mode' => 20])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        $count[9]['refund'] = self::where($filter)->where(['order_status' => 40])->where('create_time','>',$star)->where('create_time','<',$end)->count();
        return $count;
    }

}
